package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIDWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Autowired
    private IVoucherOrderService voucherOrderService;
    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private RedisIDWorker redisIDWorker;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;

    private final static DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }
    private final BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);

//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        // 1.判断秒杀是否开始或者结束
//        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
//        if (voucher == null){
//            return Result.fail("未查询到秒杀券信息");
//        }
//        LocalDateTime beginTime = voucher.getBeginTime();
//        LocalDateTime endTime = voucher.getEndTime();
//        if(beginTime.isAfter(LocalDateTime.now())){
//            return Result.fail("秒杀未开始");
//        }
//        if(endTime.isBefore(LocalDateTime.now())){
//            return Result.fail("秒杀已经结束");
//        }
//
//        // 2.利用lua脚本判断是否有资格
//
//        Long userId = UserHolder.getUser().getId();
//        Long result = stringRedisTemplate.execute(
//                SECKILL_SCRIPT,
//                Collections.emptyList(),
//                voucherId.toString(), userId.toString()
//        );
//
//        // 2.1结果不为0，没有购买资格
//        if(result == null) return Result.fail("lua脚本执行失败");
//        int r = result.intValue();
//        if(r != 0){
//            return Result.fail(r == 1 ? "库存不足" : "重复下单");
//        }
//
//        // 2.2结果为0，有购买资格
//        // TODO 保存到阻塞队列(视频里实现的太麻烦，这里不再进行编写)
//        VoucherOrder order = new VoucherOrder();
//        long orderId = redisIDWorker.nextId("order");
//        order.setUserId(userId);
//        order.setVoucherId(voucherId);
//        order.setId(orderId);
//        orderTasks.add(order);
//
//        // 3.返回订单id
//        return Result.ok(orderId);
//    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        // 1.查询优惠券信息
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        if (voucher == null){
            return Result.fail("未查询到秒杀券信息");
        }
        // 2.判断秒杀是否开始或结束
        LocalDateTime beginTime = voucher.getBeginTime();
        LocalDateTime endTime = voucher.getEndTime();
        if(beginTime.isAfter(LocalDateTime.now())){
            return Result.fail("秒杀未开始");
        }
        if(endTime.isBefore(LocalDateTime.now())){
            return Result.fail("秒杀已经结束");
        }
        // 3.判断库存是否充足
        if (voucher.getStock() < 1){
            return Result.fail("库存不足");
        }
        Long id = UserHolder.getUser().getId();
//        SimpleRedisLock lock = new SimpleRedisLock("order:" + id, stringRedisTemplate);
        RLock lock = redissonClient.getLock("lock:order:" + id);
        boolean tryLock = lock.tryLock();
        if(!tryLock){
            return Result.fail("不允许重复下单");
        }
        try {
            return voucherOrderService.createVoucherOrder(voucher);
        }finally {
            lock.unlock();
        }
    }

    @Transactional
    public Result createVoucherOrder(SeckillVoucher voucher) {
        Long userId = UserHolder.getUser().getId();
        int count = query().eq("user_id",userId)
                        .eq("voucher_id",voucher.getVoucherId()).count();
        if(count > 0){
            return Result.fail("用户已经购买过一次");
        }

        // 4.扣减库存（这里可能要注意一下事务）
        boolean update = seckillVoucherService.update().setSql("stock = stock - 1")
                .eq("voucher_id", voucher.getVoucherId())
                .gt("stock", 0)
                .update();
        if(!update){
            return Result.fail("库存不足");
        }
        // 5.创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setVoucherId(voucher.getVoucherId());
        long orderId = redisIDWorker.nextId("order");
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        save(voucherOrder);
        return Result.ok(orderId);
    }
}
